﻿namespace IBTrader.Modules.Export
{
    using AxTWSLib;
    using IBApi;
    using IBTrader.Modules.Configuration;
    using IBTrader.Modules.Tws;
    using System;
    using System.Text;
    using System.Xml;

    class ExportExecutions
    {
        private const int RequestId = 2;
        private readonly IIB tws;
        private XmlTextWriter writer;
        internal ExportExecutions(IIB tws)
        {
            this.tws = tws;
        }
        internal string DefaultFileName(object clientId)
        {
            return string.Format("{0:" + Times.DateFormat + "}_{1}_Executions.xml", DateTime.Now, clientId);
        }
        internal void Start(string fileName, DateTime dt)
        {
            writer = new XmlTextWriter(fileName, Encoding.Default);
            writer.Formatting = Formatting.Indented;
            writer.WriteStartElement("Executions");

            tws.execDetails += Details;
            tws.execDetailsEnd += End;

            var filter = tws.CreateExecutionFilter() as ExecutionFilter;
            filter.Time = dt.ToString("yyyyMMdd");
            tws.reqExecutions(RequestId, filter);
        }
        private void Details(object sender, ExecDetailsEventArgs e)
        {
            if (e.reqId != RequestId) return;

            writer.WriteStartElement("Execution");
            new XmlInterfaceSerializer(typeof(Contract)).Serialize(writer, e.contract);
            new XmlInterfaceSerializer(typeof(Execution)).Serialize(writer, e.execution);
            writer.WriteEndElement();
        }
        private void End(object sender, _DTwsEvents_execDetailsEndEvent e)
        {
            if (e.reqId != RequestId) return;

            writer.WriteEndElement();
            writer.Close();

            tws.execDetails -= Details;
            tws.execDetailsEnd -= End;
        }
    }
}